<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>广学古诗文</title>
    <link rel="stylesheet" href="https://gxwtf.cn/css/fa-pro/css/all.min.css">
    <link rel="stylesheet" href="/css/basic.css">
    <style>
        .poem-container {
            padding: 24px;
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }

        .poem-card {
            background: #fff;
            border: 1px solid var(--primary-color);
            border-radius: 8px;
            padding: 16px;
            position: relative;
            cursor: pointer;
        }

        .poem-title {
            color: var(--primary-color);
            margin: 0 0 8px;
            font-size: 20px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 100%;
            position: relative;
        }

        .poem-title:hover::after {
            content: attr(data-title);
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 6px 12px;
            border-radius: 4px;
            font-size: 14px;
            white-space: normal;
            width: max-content;
            max-width: 300px;
            z-index: 10;
            pointer-events: none;
        }

        .poem-meta {
            color: #6c757d;
            font-size: 14px;
            margin-bottom: 12px;
        }

        .tag-container {
            display: flex;
            gap: 6px;
            margin-top: 12px;
            flex-wrap: wrap;
        }

        .tag {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            border: 1px solid;
        }

        .tag-required {
            color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .tag-literary {
            color: var(--tag-color);
            border-color: var(--tag-color);
        }

        .poem-preview {
            line-height: 1.6;
            color: #495057;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            overflow: hidden;
            max-height: calc(3 * 1.6em);
            /* 根据行高动态计算 */
        }

        .search-section {
            padding: 20px 20px;
            background: #fff;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .search-container {
            max-width: 800px;
            margin: 0 auto;
            position: relative;
        }

        .search-input {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid var(--primary-color);
            border-radius: 25px;
            font-size: 16px;
            transition: all 0.3s;
        }

        .search-input:focus {
            outline: none;
            box-shadow: 0 0 8px rgba(163, 31, 36, 0.3);
        }

        .filter-tags {
            margin-top: 16px;
            display: grid;
            grid-template-rows: repeat(2, 1fr);
            gap: 12px;
        }

        .filter-group {
            padding: 12px;
        }

        .filter-title {
            color: var(--primary-color);
            font-size: 14px;
            margin-bottom: 8px;
        }

        .tag-btn {
            padding: 8px 16px;
            border-radius: 20px;
            border: 2px solid #ddd;
            background: #fff;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 14px;
            margin: 4px;
            position: relative;
            overflow: hidden;
        }

        .tag-btn.active[data-type="教材"] {
            background: linear-gradient(45deg, #A31F24, #D32F2F);
            color: white;
            border-color: transparent;
            box-shadow: 0 4px 12px rgba(163, 31, 36, 0.3);
        }

        .tag-btn.active[data-type="文体"] {
            background: linear-gradient(45deg, #1890ff, #4dabf7);
            color: white;
            border-color: transparent;
            box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
        }

        .tag-btn.active[data-type="题材"] {
            background: linear-gradient(45deg, #32CD32, #4CAF50);
            color: white;
            border-color: transparent;
            box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
        }

        .tag-btn.active[data-type="其他"] {
            background: linear-gradient(45deg, #FFA500, #FF8C00);
            color: white;
            border-color: transparent;
            box-shadow: 0 4px 12px rgba(255, 140, 0, 0.3);
        }

        .selected-tags {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-top: 12px;
        }

        .no-results-container {
            display: none;
            text-align: center;
        }

        .no-results {
            color: #6c757d;
            font-size: 18px;
        }

        .no-results i {
            font-size: 64px;
            color: var(--primary-color);
            margin-top: 10px;
            margin-bottom: 10px;
        }
    </style>
    <script src="/js/footer.js"></script>
</head>

<body>
    <nav class="navbar">
        <a href="/" class="navbar-title">广学古诗文</a>
        <div class="version-toggle">
            <span>高中版</span>
            <i id="versionSwitch" class="fas fa-toggle-on toggle-icon"></i>
        </div>
    </nav>

    <section class="search-section">
        <div class="search-container">
            <input type="text" class="search-input" placeholder="搜索古诗文..." id="searchInput">

            <div class="selected-tags" id="selectedTags"></div>

            <div class="filter-tags">
                    <div class="filter-group">
                        <div class="filter-title">教材</div>
                        <div class="tag-group">
                            <button class="tag-btn" data-type="教材" data-value="必修上">必修上</button>
                            <button class="tag-btn" data-type="教材" data-value="必修下">必修下</button>
                            <button class="tag-btn" data-type="教材" data-value="选必上">选必上</button>
                            <button class="tag-btn" data-type="教材" data-value="选必中">选必中</button>
                            <button class="tag-btn" data-type="教材" data-value="选必下">选必下</button>
                        </div>
                    </div>

                    <div class="filter-group">
                        <div class="filter-title">文体</div>
                        <div class="tag-group">
                            <button class="tag-btn" data-type="文体" data-value="诗">诗</button>
                            <button class="tag-btn" data-type="文体" data-value="词">词</button>
                            <button class="tag-btn" data-type="文体" data-value="曲">曲</button>
                            <button class="tag-btn" data-type="文体" data-value="文言文">文言文</button>
                            <button class="tag-btn" data-type="文体" data-value="戏剧">戏剧</button>
                        </div>
                    </div>

                    <div class="filter-group">
                        
                        <div class="filter-title">题材</div>
                        <div class="tag-group">
                            <button class="tag-btn" data-type="题材" data-value="山水田园">山水田园</button>
                            <button class="tag-btn" data-type="题材" data-value="咏史怀古">咏史怀古</button>
                            <button class="tag-btn" data-type="题材" data-value="边塞">边塞</button>
                        </div>
                    </div>
                    
                    <div class="filter-group">
                        <div class="filter-title">其他</div>
                        <div class="tag-group">
                            <button class="tag-btn" data-type="其他" data-value="背默">背默</button>
                        </div>
                    </div>
            </div>
        </div>
    </section>

    <div class="poem-container" id="poemContainer"></div>

    <div class="no-results-container" id="noResultsContainer">
        <div class="no-results">
            <i class="fas fa-book-open"></i>
            <div style="color:var(--primary-color)">找不到您查找的古诗文</div>
        </div>
    </div>

    <div id="footer-container"></div>

    <script>
        /* ================= 全局状态 ================= */
        let currentVersion = 'senior';
        const currentFilters = { search: '', tags: {} }; // 分类存储 tags
        const selectedTags = []; // 用于显示的标签列表

        /* ============ 调整预览行数 ============ */
        function adjustPreviewHeight(card) {
            const preview = card.querySelector('.poem-preview');
            const lineHeight = parseInt(getComputedStyle(preview).lineHeight);
            const maxHeight = card.clientHeight - 120;
            const availableLines = Math.floor(maxHeight / lineHeight);
            preview.style.webkitLineClamp = Math.max(1, availableLines);
        }

        /* ================= 构建查询参数 ================= */
        function buildQueryParams() {
            const params = new URLSearchParams();
            params.append('version', currentVersion);

            if (currentFilters.search) {
                params.append('search', currentFilters.search);
            }

            if (Object.keys(currentFilters.tags).length > 0) {
                // 按类别解析标签为字符串
                const tagsString = Object.values(currentFilters.tags)
                    .map(group => group.join(','))
                    .join(';');
                params.append('tags', tagsString);
            }

            return params.toString();
        }

        /* ============== 更新已选标签显示 ============== */
        function updateSelectedTagsDisplay() {
            const selectedTagsContainer = document.getElementById('selectedTags');
            selectedTagsContainer.innerHTML = selectedTags
                .map(tag => `
                    <div class="tag-btn active" data-value="${tag}" onclick="removeTag('${tag}')">
                        ${tag} <i class="fas fa-times"></i>
                    </div>
                `)
                .join('');
        }

        /* ============== 标签状态更新处理函数 ============== */
        function updateTagState(btn) {
            btn.classList.toggle('active');

            const category = btn.closest('.filter-group').querySelector('.filter-title').textContent.trim();
            const value = btn.dataset.value;

            // 更新分类存储的 tags
            if (!currentFilters.tags[category]) {
                currentFilters.tags[category] = [];
            }

            if (btn.classList.contains('active')) {
                currentFilters.tags[category].push(value);
                selectedTags.push(value); // 添加到显示的标签列表
            } else {
                currentFilters.tags[category] = currentFilters.tags[category].filter(tag => tag !== value);
                if (currentFilters.tags[category].length === 0) {
                    delete currentFilters.tags[category];
                }
                const index = selectedTags.indexOf(value);
                if (index > -1) {
                    selectedTags.splice(index, 1); // 从显示的标签列表中移除
                }
            }

            // 输出调试日志
            console.log('当前分类存储的标签:', currentFilters.tags);
            console.log('当前显示的标签:', selectedTags);

            // 更新显示和重新加载数据
            updateSelectedTagsDisplay();
            loadData();
        }

        /* ============== 删除标签 ============== */
        function removeTag(tag) {
            // 从 selectedTags 中移除
            const index = selectedTags.indexOf(tag);
            if (index > -1) {
                selectedTags.splice(index, 1);
            }

            // 从分类存储的 tags 中移除
            for (const category in currentFilters.tags) {
                currentFilters.tags[category] = currentFilters.tags[category].filter(t => t !== tag);
                if (currentFilters.tags[category].length === 0) {
                    delete currentFilters.tags[category];
                }
            }

            // 在 filter-tags 中找到对应的标签并调用 updateTagState
            const tagButton = document.querySelector(`.filter-tags .tag-btn[data-value="${tag}"]`);
            if (tagButton) {
                updateTagState(tagButton); // 调用标签状态更新函数
            }

            // 更新显示和重新加载数据
            updateSelectedTagsDisplay();
            loadData();
        }

        /* ============== 渲染诗文卡片 ============== */
        function renderPoems(poems) {
            const container = document.getElementById('poemContainer');
            const noResults = document.getElementById('noResultsContainer');
            if (poems.length === 0) {
                // 显示无结果提示
                container.innerHTML = '';
                noResults.style.display = 'block';
            } else {
                // 隐藏无结果提示
                noResults.style.display = 'none';

                // 渲染诗文卡片
                container.innerHTML = poems.map(poem => `
                    <div class="poem-card" onclick="location.href='/${encodeURIComponent(poem.title)}'">
                        <h2 class="poem-title" data-title="${poem.title}">${poem.title}</h2>
                        <div class="poem-meta">【${poem.dynasty}】${poem.author}</div>
                        <div class="poem-preview">${poem.content.map(c => c.line).join('')}</div>
                        <div class="tag-container">
                            ${poem.tags.map(tag => `
                                <div class="tag ${tag.includes('必修') ? 'tag-required' : 'tag-literary'}">
                                    ${tag}
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `).join('');

                container.querySelectorAll('.poem-card').forEach(adjustPreviewHeight);
            }
        }

        /* ============== 标签点击事件绑定 ============== */
        document.querySelectorAll('.tag-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                updateTagState(btn);
            });
        });

        /* ============== 数据加载 ============== */
        async function loadData() {
            try {
                const res = await fetch(`/poem?${buildQueryParams()}`);
                console.log('请求参数:', buildQueryParams());
                const poems = await res.json();
                renderPoems(poems);
            } catch (err) {
                console.error('加载失败:', err);
            }
        }

        /* ============== 事件监听 ============== */
        document.getElementById('versionSwitch').addEventListener('click', async () => {
            currentVersion = currentVersion === 'senior' ? 'junior' : 'senior';
            const toggle = document.getElementById('versionSwitch');
            toggle.classList.toggle('fa-toggle-on');
            toggle.classList.toggle('fa-toggle-off');
            toggle.parentNode.querySelector('span').textContent = currentVersion === 'senior' ? '高中版' : '初中版';
            loadData();
        });

        let searchTimer;
        document.getElementById('searchInput').addEventListener('input', (e) => {
            clearTimeout(searchTimer);
            currentFilters.search = e.target.value;
            searchTimer = setTimeout(loadData, 500);
        });

        // 初始化加载
        loadData();
    </script>
</body>

</html>